extends "res://scene/object/plane.gd"

# 掉落道具数量
@export var fall_item:int = 1
@export var exp = 10

var can_move:bool
@onready var move_timer = $moveTimer
@onready var stop_timer = $stopTimer

@onready var leave_timer = $leaveTimer



# 敌人入场和出场位置
var fadein_pos
var fadeout_pos

var direction = 1

func _ready():
	super._ready()
	state = global.STATE_FADEIN
	set_verlocity()
	
	fadein_pos = Vector2(position.x, 90)
	fadeout_pos = Vector2(position.x, -80)
	
	
	hpBar.max_value = maxhp
	hpBar.value = hp
	
	#if maxhp>1:
		#hpBar.max_value = maxhp
		#hpBar.value = hp
	#else:
		#hpBar.hide()
	
	
	
func set_verlocity():
	velocity.x = direction * 10 * agi
	
func _process(delta):
	
	match(state):
		global.STATE_FADEIN:
			can_move = false
			shoot_timer.stop()
			move_timer.stop()
			position.x = move_toward(position.x, fadein_pos.x, 5)
			position.y = move_toward(position.y, fadein_pos.y, 5)
			
			if position.distance_squared_to(fadein_pos) < 1e-4:
				# 到达入场位置
				state = global.STATE_ACTIVE
				can_move = true	
				shoot_timer.start()
				move_timer.start()
				leave_timer.start()
				
		global.STATE_FADEOUT:
			can_move = false
			shoot_timer.stop()
			move_timer.stop()
			position.y = move_toward(position.y, fadeout_pos.y, 10)
			if abs(position.y - fadeout_pos.y)<1: 
				queue_free()
				
		global.STATE_ACTIVE:
			if can_move:
				move_and_slide()	




func _on_move_timer_timeout():
	randomize()
	stop_timer.wait_time = randf_range(0.5, 1)
	stop_timer.start()
	can_move = false
	print("stop")


func _on_stop_timer_timeout():
	print("is_on_wall="+str(is_on_wall()))
	if is_on_wall():
		direction = -direction
		set_verlocity()
		
	elif stop_timer.wait_time > 0.5:
		randomize()
		var rand_val = randf_range(0,1)
		if rand_val > 0.5 :
			direction = -direction
			set_verlocity()
	
	move_timer.start()
	can_move = true		
	print("move")



func _on_shoot_timer_timeout():
		fire(true)
				


func _on_leave_timer_timeout():
	state = global.STATE_FADEOUT

func _on_destroy_timer_timeout():
	print("_on_destroy_timer_timeout enemy")
	
	# 物品掉落
	if fall_item > -1:
		randomize()
		if randf_range(0,1)>0.4:
			var item = preload("res://scene/object/item.tscn").instantiate()
			item.position = global_position
			item.id = fall_item
			get_parent().add_child(item)
	
	# 给玩家增加经验值
	if global.player!=null:
		print("exp="+str(exp))
		global.player.add_exp(exp)
	
	super._on_destroy_timer_timeout()
